/**
 *
 * @param {Array} routes
 * @param {Array} routeList
 * @param {Object} routeMap
 */
export default function createRouteMap(routes, routeList = [], routeMap = {}) {
  // 路由需递归处理
  addRouteToSave(routes, routeList, routeMap);

  return {
    routeList,
    routeMap
  }
}

/**
 * 递归处理路由函数
 * @param {Array} routes
 * @param {Array} routeList
 * @param {Object} routeMap
 */
function addRouteToSave(routes, routeList, routeMap, parent) {
  for (const route of routes) {
    const { name, component, children } = route;
    let { path } = route;

    if (path !== undefined && component) {
      if (path.startsWith("/")) {
        // 代表该路由从根路由开始
      } else {
        path = parent ? `${parent.path}/${path}` : path;
      }

      if (routeMap[path]) {
        console.error(`The component ${name || path} already exists`);
      } else {
        routeList.push(path);
        route.path = path;
        route.parent = parent;
        routeMap[path] = route;
      }

    } else {
      console.error("path or component does not exist");
    }

    if (children && Array.isArray(children)) {
      addRouteToSave(children, routeList, routeMap, route);
    }
  }
}
